<template>
    <div>
        <div @click="clickBarChart" class="vue-flow-model">
            <n-icon size="30" color="#18A058">
                <ChartTreemap/>
            </n-icon>
            <Handle id="ChartTreemap-inlet" type="target" :position="Position.Left"
                    :is-valid-connection="props.isValidSourcePos"/>
            <Handle id="ChartTreemap-export" type="source" :position="Position.Right"
                    :is-valid-connection="props.isValidTargetPos"/>
        </div>
        <span>树状图</span>
        <n-drawer v-model:show="active" :width="'80vw'">
            <n-drawer-content>
                <template #header>
                    树状图
                </template>
                <!--获取上级节点数据 进行去除空值-->
                <n-space>
                    <n-button @click="getSuperiorData">
                        <template #icon>
                            <n-icon>
                                <Login/>
                            </n-icon>
                        </template>
                        获取上级节点数据
                    </n-button>
                    <n-button
                        @click="drawing"
                        :disabled="!selects.name||!selects.proportion"
                    >
                        <template #icon>
                            <n-icon>
                                <ChartTreemap/>
                            </n-icon>
                        </template>
                        绘图
                    </n-button>
                    <n-select
                        class="n-select-one"
                        placeholder="所属系列(可选)"
                        v-model:value="selects.group"
                        :options="groupOption"
                        label-field="title"
                        value-field="key"
                        :disabled="!props.data.data.title"
                    />
                    <n-select
                        class="n-select-one"
                        placeholder="系列名称(必选)"
                        v-model:value="selects.name"
                        :options="props.data.data.title"
                        label-field="title"
                        value-field="key"
                        :disabled="!props.data.data.title"
                    />
                    <n-select
                        class="n-select-one"
                        placeholder="系列值(必选)"
                        v-model:value="selects.proportion"
                        :options="props.data.data.title"
                        label-field="title"
                        value-field="key"
                        :disabled="!props.data.data.title"
                    />

                </n-space>
                <!--展示数据-->
                <!-- 为ECharts准备一个具备大小（宽高）的Dom -->
                <div ref="chartDom" style="width: 100%;height:80%;"></div>
                <template #footer>
                    <n-button @click="active=false">完成</n-button>
                </template>
            </n-drawer-content>
        </n-drawer>
    </div>
</template>

<script setup>

import {Handle, Position} from "@vue-flow/core";
import {ChartTreemap, Login} from "@vicons/carbon";
import {useElementsStore} from "@/stores/elements";
import * as echarts from 'echarts';


const props = defineProps(['isValidTargetPos', 'isValidSourcePos', 'id', 'data'])
const elements = useElementsStore()
const clickBarChart = () => {
    active.value = true
    setTimeout(() => {
        if (props.data.selects) {
            Object.keys(props.data.selects).forEach(key => {
                if (selects.value.hasOwnProperty(key)) {
                    selects.value[key] = props.data.selects[key];
                }
            });
        }
        if (selects.value.name !== null && selects.value.proportion !== null) {
            drawing();
        }
    }, 1)
}
// 抽屉
const active = ref(false)
const selects = ref({
    group: null,
    name: null,
    proportion: null,
})
const groupOption = computed(() => {
    console.log(props.data.data.title)
    let array = props.data.data.title === undefined ? [] : props.data.data.title
    return [{title: '(不选)', key: null}, ...array]
})


const option = ref(null)
let chartDom = ref(null)

const getSuperiorData = () => {
    // 获取上级节点数据
    for (let i of elements.elements) {
        if (i['target'] === props.id) {
            for (let j of elements.elements) {
                if (j.id === i['source']) {
                    props.data.data = {...j.data.data}
                    props.data.data.title.map(s => {
                        // 移除可修改
                        delete s.render
                        return s
                    })
                    return
                }
            }
        }
    }
}
const drawing = () => {
    let data = []
    if (selects.value.group === null) { // 不选择组
        for (let i of props.data.data.data) {// 循环全部数据
            let groupName = i[selects.value.name]
            data.push({
                name: groupName,
                value: i[selects.value.proportion]
            })
        }
    } else { // 选组
        for (let i of props.data.data.data) {// 循环全部数据
            let isNewGroup = true; // 是否新的组
            let groupName = i[selects.value.group];
            for (let j of data) { // 循环data
                if (j.name === groupName) { // 如果找到该组名
                    j.children.push({ // 在该组添加数据
                        name: i[selects.value.name],
                        value: i[selects.value.proportion]
                    })
                    isNewGroup = false // 标记为旧的组
                    break
                }
            }
            if (isNewGroup) {  // 如果是新组
                data.push({
                    name: groupName,
                    children: [{
                        name: i[selects.value.name],
                        value: i[selects.value.proportion]
                    }]
                })
            }
        }
        data.map(i => {
            let value = 0
            for (let j of i.children) {
                value = value + +j.value
            }
            i.value = value
            return i
        })
    }

    console.log(data)

    function getLevelOption() {
        return [
            {
                itemStyle: {
                    borderColor: '#777',
                    borderWidth: 0,
                    gapWidth: 1
                },
                upperLabel: {
                    show: false
                }
            },
            {
                itemStyle: {
                    borderColor: '#777777',
                    borderWidth: 5,
                    gapWidth: 1
                },
                emphasis: {
                    itemStyle: {
                        borderColor: '#fff'
                    }
                }
            },
            {
                colorSaturation: [0.35, 0.5],
                itemStyle: {
                    borderWidth: 5,
                    gapWidth: 1,
                    borderColorSaturation: 0.6
                }
            }
        ];
    }

    // 绘图
    option.value = {
        title: {
            text: '树状图',
            left: 'center'
        },
        toolbox: {
            show: true,
            feature: {
                saveAsImage: {}
            }
        },
        tooltip: {
            formatter: function (info) {
                var value = info.value;
                var treePathInfo = info.treePathInfo;
                var treePath = [];
                for (var i = 1; i < treePathInfo.length; i++) {
                    treePath.push(treePathInfo[i].name);
                }
                return [
                    '<div class="tooltip-title">' +
                    echarts.format.encodeHTML(treePath.join('/')) +
                    '</div>',
                    '比重: ' + echarts.format.addCommas(value) + ' '
                ].join('');
            }
        },
        series: [
            {
                name: '总体',
                type: 'treemap',
                visibleMin: 300,
                label: {
                    show: true,
                    formatter: '{b}'
                },
                upperLabel: {
                    show: true,
                    height: 30
                },
                itemStyle: {
                    borderColor: '#fff'
                },
                levels: getLevelOption(),
                data: data
            }
        ]
    }

    let myChart = echarts.init(chartDom.value);

    console.log(option.value)
    props.data.selects = selects.value
    props.data.option = option.value
    option.value && myChart.setOption(option.value);
}
</script>

<style scoped lang="less">
.n-select-one {
    width: 8vw;
}

.n-select-two {
    width: 45vw;
}

.n-space {
    .n-space-span {
        position: relative;
        top: 18%;
    }
}
</style>